﻿using NFine.Util;
using NFine.WeiXin.Model;
using System;
using System.Collections.Generic;
using System.Text;

namespace NFine.WeiXin.Service
{
    public class WxUserService : DbContext
    {
        public void Subscribe(string toUserName, string fromUserName, DateTime subscribeTime)
        {
            NFine.WeiXin.Model.WxAccountModel wxAccountModel = WxAccountDb.GetSingle(it => it.OriginalId == toUserName);
            WxUserModel wxUserModel = WxUserDb.GetSingle(it => it.AppId == wxAccountModel.AppId && it.OpenId == fromUserName);
            if (wxUserModel == null)
            {
                wxUserModel = new WxUserModel();
                wxUserModel.Id = IdWorkerHelper.GenId64();
                wxUserModel.AppId = wxAccountModel.AppId;
                wxUserModel.OpenId = fromUserName;
                wxUserModel.SubscribeTime = subscribeTime;
                wxUserModel.SubscribeStatus = 1;
                WxUserDb.Insert(wxUserModel);
            }
            else
            {
                wxUserModel.SubscribeStatus = 1;
                wxUserModel.SubscribeTime = subscribeTime;
                WxUserDb.Update(wxUserModel);
            }
        }
        public void Unsubscribe(string toUserName, string fromUserName, DateTime createTime)
        {
            NFine.WeiXin.Model.WxAccountModel wxAccountModel = WxAccountDb.GetSingle(it => it.OriginalId == toUserName);
            WxUserModel wxUserModel = WxUserDb.GetSingle(it => it.AppId == wxAccountModel.AppId && it.OpenId == fromUserName);
            if (wxUserModel != null)
            {
                wxUserModel.SubscribeStatus = 0;
                wxUserModel.SubscribeTime = createTime;
                WxUserDb.Update(wxUserModel);
            }
        }
    }
}
